<?php

namespace App\Http\Servers\Admin;

use App\Banner;

class BannerServer
{
    private $banner;
    private $imageServer;

    public function __construct(Banner $banner, ImageServer $imageServer)
    {
        $this->banner = $banner;
        $this->imageServer = $imageServer;
    }

    //只有超级管理员才能操作
    public function noPower()
    {
        return false;
        if (!(bool)\Auth::guard('admin')->user()->is_root) {
            $message['message'] = message(false, '操作失败', '该操作需要超级管理员的权限!');
            return back()->with($message);
        }
    }

    //标签中存在Banner图片 无法删除
    public function hasBanner($label)
    {
        $count = $this->banner->where('label', $label)->count();
        if ($count > 0) {
            $message['message'] = message(false, '删除失败', '该标签中存在Banner图片,无法删除!');
            return back()->with($message);
        }
    }

    //只有超级管理员或者本图片上传者可以操作
    public function noPowerByAdminAndAuthor($author)
    {
        return false;
        if (!((bool)\Auth::guard('admin')->user()->is_root || \Auth::guard('admin')->user()->id == $author)) {
            return message(false, '操作失败', '该操作需要超级管理员或本分类作者的权限!');
        } else {
            return false;
        }
    }

    //删除Banner图片
    public function delBanner($request)
    {
        if ($request->has('del')) {
            $banner = $this->banner->findorfail($request->del);

            if ($message = $this->noPowerByAdminAndAuthor($banner->author)) {
                return back()->with($message);
            }

            $result = $banner->delete();
            if ($result) {
                $this->imageServer->deleteImage($banner->image);
                $message['message'] = message(true, '删除成功', 'Banner图片删除成功!');
            } else {
                $message['message'] = message(false, '删除失败', 'Banner图片删除失败!');
            }
            return back()->with($message);
        }
    }

    //修改Banner图片状态
    public function bannerStatusChange($request)
    {
        if ($request->has('change')) {
            $banner = $this->banner->findorfail($request->id);
            $change = $request->change;

            if (array_search($change, ['status']) === false) {
                $message['message'] = message(false, '修改失败', 'Banner该属性无法修改!');
                return back()->with($message);
            }

            $banner->$change = (bool)$banner->$change ? 0 : 1;
            $result = $banner->save();
            if ($result) {
                $message['message'] = message(true, '修改成功', 'Banner状态修改成功!');
            } else {
                $message['message'] = message(fasle, '修改失败', 'Banner状态修改失败!');
            }
            return back()->with($message);
        }
    }
}